#!/usr/bin/env python
"""Weather grab script which uses Pymetar v0.13 module.

Dumps fetched data into an SQLite3 database
"""

__RCS__ = '$Id$'
__version__='$Revision: $'
__initialdate__ = 'October 2007'
__author__='Darren Paul Griffith, http://madphilosopher.ca/'

__license__ = '''Copyright (c) 2007, Darren Paul Griffith, All rights reserved.

Redistribution and use in source and binary forms, with or without modification,
are permitted provided that the following conditions are met:

* Redistributions of source code must retain the above copyright notice,
  this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice,
  this list of conditions and the following disclaimer in the documentation
  and/or other materials provided with the distribution.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS 'AS IS'
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.'''


import sys
import pymetar
import sqlite3 as sqlite
import time

DEBUG = False
DATABASE = '/db/wg3.db'
DATABASE2 = '/db/code.db'
# CODES = ['CYOJ', 'CYXD', 'CYEG', 'ZBAA']
WEBSET = ['CYOJ', 'CYFS', 'CYPE', 'CXHP', 'CYXD', 'CYEG']


def usage():
   '''Usage of this module'''
   print "wg3: grab METAR reports and stuff in metar database"
   print "Usage: wg3 CODE [...]"
   sys.exit()


if __name__ == "__main__":

    if DEBUG:
        print "pymetar version:     ", pymetar.__version__    # pymetar lib version number
        print "Using pysqlite file: ", sqlite.__file__        # from the extension module
        print "pysqlite version:    ", sqlite.version         # from the extension module
        print "SQLite version:      ", sqlite.sqlite_version  # from the sqlite library code
        print

    # get the airport codes from the command line
    args = sys.argv[1:]
    if len(args) == 0 :
        usage()
    else:
        CODES = args
        if DEBUG: print "CODES: ", CODES

    # connect to the database
    connection = sqlite.connect(DATABASE)
    cursor = connection.cursor()
    connection2 = sqlite.connect(DATABASE2)
    cursor2 = connection2.cursor()

    for station_id in CODES:

        station_id = station_id.upper()

        if DEBUG: print "Fetching station:", station_id

        # run the necessary pymetar stuff to fetch and parse the METAR
        rf = pymetar.ReportFetcher(station_id)
        report = rf.FetchReport()
        rp = pymetar.ReportParser()
        pr = rp.ParseReport(report)

        if DEBUG: 
            print pr.code
            print station_id, pr.temp, pr.dewp
            print

        # store the values in the database
        cursor.execute("insert into metar(station_id, givenstationid, fullreport, code, temp, windspeed, winddir, windcomp, vis, dewp, humid, press, slp, weather, sky, fulln, cycle, rtime, pixmap, latitude, longitude, altitude, stat_city, stat_country, reporturl, latf, longf) values(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)", (station_id, pr.givenstationid, pr.fullreport, pr.code, pr.temp, pr.windspeed, pr.winddir, pr.windcomp, pr.vis, pr.dewp, pr.humid, pr.press, pr.slp, pr.weather, pr.sky, pr.fulln, pr.cycle, pr.rtime, pr.pixmap, pr.latitude, pr.longitude, pr.altitude, pr.stat_city, pr.stat_country, pr.reporturl, pr.latf, pr.longf))

        if station_id in WEBSET:
            cursor2.execute("insert into metar(station_id, code, cycle) values(?,?,?)", (station_id, pr.code, pr.cycle))

        # write out some data to the filesystem for munin plugins
        filename = station_id + ".dat"
        f = open(filename, "w") 
        f.write("%s %s\n" % (station_id, pr.rtime))
        f.write("%s\n"    % (pr.temp))
        f.close()

        if not DEBUG: time.sleep(5)

    connection.commit()   # This must be done to commit the changes
    cursor.close()
    connection.close()
    connection2.commit()   # This must be done to commit the changes
    cursor2.close()
    connection2.close()

    sys.exit(0)
